package com.fin.quant.web.controller;


import com.fin.quant.rpc.common.Result;
import com.fin.quant.web.service.StockPriceDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@CrossOrigin
@RequestMapping("/dl/api/upload")
@RestController
@Slf4j
public class UploadController {

    @Autowired
    private StockPriceDataService stockPriceDataService;

    @RequestMapping("/refreshFile")
    public Result refreshFile() throws IOException, InvalidFormatException {
        stockPriceDataService.refreshFile();
        return Result.createSuccessResult();
    }

    @RequestMapping("/uploadFile")
    public Result uploadFile(@RequestParam(value = "password", required = false) String password, @RequestParam(required = false) MultipartFile file) throws IOException, InvalidFormatException {
        log.info("uploadFile password={}", password);
        if (file != null) {
            log.info(file.getOriginalFilename());
            Path tempFile = Files.createTempFile("stockData", ".xlsx");
            file.transferTo(tempFile);
            stockPriceDataService.refreshFile(tempFile.toFile());
        }

        return Result.createSuccessResult();
    }
}
